package cn.walls1717.juc.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * refFieldUpdater测试
 *
 * @author walls1717
 * @create 2022/12/12 17:22
 **/
@Slf4j
public class AtomicReferenceFieldUpdaterDemo {

    public static void main(String[] args) {
        MyVar myVar = new MyVar();

        for (int i = 1; i <= 5; i++) {
            new Thread(()->{
                myVar.init(myVar);
            }).start();
        }
    }
}

@Slf4j
class MyVar {
    public volatile Boolean isInit = Boolean.FALSE;

    AtomicReferenceFieldUpdater<MyVar, Boolean> updater =
        AtomicReferenceFieldUpdater.newUpdater(MyVar.class, Boolean.class, "isInit");

    public void init(MyVar myVar) {
        if (updater.compareAndSet(myVar, Boolean.FALSE, Boolean.TRUE)) {
            log.info("init");
        } else {
            log.info("already init");
        }
    }
}
